<template>
  <div class="orderDetail">
    <PageContainer title="确认订单" back no-tab>
      <div class="order-card">
        <div class="order-header">
          <ProductCardLandscape
            :img="productInfo.imgList"
            :price="productInfo.price"
            :title="productInfo.name"
            :orderType="orderType"
          />
        </div>
        <div class="order-info">
          <div class="label-value">
            <div class="label">剩余库存</div>
            <div class="value">{{ productInfo.stock }}</div>
          </div>
          <div v-if="Number(orderType) === 1" class="label-value">
            <div class="label">购买后可兑换积分</div>
            <div class="value">{{ productInfo.exchangePoint }}积分</div>
          </div>
          <div
            v-if="Number(orderType) !== 2"
            class="label-value"
            @click="onCouponClick"
          >
            <div class="label">卡券</div>
            <div class="value">
              {{ couponsInfo?.name || "请选择" }}
            </div>
          </div>
          <div class="label-value">
            <div class="label">待付金额</div>
            <div class="value">
              {{ currentPrice || productInfo.price }}{{ Number(orderType) === 2 ? "积分" : "元" }}
            </div>
          </div>
        </div>
      </div>

      <div class="btns">
        <u-button
          :plain="true"
          text="取消"
          :customStyle="customStyle"
          color="#2A2727"
          @click="goback"
        ></u-button>
        <u-button
          type="primary"
          text="确认下单"
          :customStyle="customStyle"
          color="#282828"
          @click="confirm"
        ></u-button>
      </div>
    </PageContainer>
    <u-popup
      :show="showCoupon"
      mode="bottom"
      @close="onCouponClose"
      @open="onCouponOpen"
    >
      <div class="coupon-wrapper">
        <div class="coupon-list">
          <div
            v-for="(item, index) in couponDataList"
            :key="index"
            :class="['item', item.status !== 0 ? 'disabled' : '']"
          >
            <div class="price">
              <span v-if="item.type === 2">{{ String(item.totalCoupon * 100).replace(/(0+)$/g,"") }}折</span>
              <span v-else>￥{{ item.totalCoupon }}</span>
            </div>
            <div class="order-info">
              <div class="title">{{ item.name }}</div>
              <div class="time">到期时间: {{ item.expireDate }}</div>
            </div>
            <div class="coupon-btn" @click="onCouponBtnClick(item)">
              {{ couponsInfo.id === item.id ? "撤销" : "使用" }}
            </div>
          </div>
          <u-loadmore
            status="nomore"
            loadmoreText="加载更多"
            nomoreText="暂无更多卡券"
          />
        </div>
      </div>
    </u-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import PageContainer from "@/components/PageContainer/index.vue";
import ProductCard from "@/components/ProductCard/index.vue";
import ProductCardLandscape from "@/components/ProductCardLandscape/index.vue";
import RecommendList from "@/components/RecommendList/index.vue";
import { useRouter } from "@/hooks/useRouter";
import { addOrder } from "@/api";
import { useToast } from "@/hooks/useToast";
import {
  getProductDetail,
  getPointProductDetail,
  getPrice,
} from "@/api/product";
import { couponList } from "@/api";

const { back, getPageQuery } = useRouter();

const query = ref({});
const toast = useToast();

const item = ref({});

const customStyle = ref({
  width: uni.upx2px(330) + "px",
  height: uni.upx2px(92) + "px",
  "border-radius": 0,
  border: "1px solid rgba(63,60,60,0.3)",
});
const productId = ref("");
const orderType = ref("");
const productInfo = ref({
  name: "",
  price: 0,
  count: 0,
  labelList: [],
  description: "",
  imgList: null,
  stock: 0,
  exchangePoint: 0,
  dressProjectId: 0,
});
// const currentPrice = computed(() => {
//   const price = productInfo.value.price;
//   if (!couponsInfo.value.id) return price;
//   if (couponsInfo.value.type === 2) {
//     return Math.floor(price * couponsInfo.value.totalCoupon * 100) / 100;
//   }
//   return price - couponsInfo.value.totalCoupon;
// });

const initProductInfo = () => {
  const apiFn =
    orderType.value === 2 ? getPointProductDetail : getProductDetail;
  apiFn(productId.value).then((res) => {
    productInfo.value = {
      name: res.name,
      price: orderType.value === 2 ? res.pointPrice : res.price,
      count: res.stock,
      description: res.remark || "",
      imgList: res.imageList || null,
      labelList: res.label ? res.label.split(",") : [],
      stock: res.stock,
      exchangePoint: 0,
      dressProjectId: res.dressProjectId,
    };

    console.log("积分商品----", productInfo.value);
  });
};
onMounted(() => {
  const query = getPageQuery();
  productId.value = query.id;
  orderType.value = Number(query.orderType) || 1;
  console.log("orderType.value----", orderType.value);
  initProductInfo();
  if (orderType.value === '1') {
    getRealPrice();
  }
});
// 卡券相关功能---------------
const couponsInfo = ref({});
const couponDataList = ref([]);
const showCoupon = ref(false);
const onCouponClick = () => {
  showCoupon.value = true;
  getCouponList();
};
const onCouponClose = () => {
  showCoupon.value = false;
};
const onCouponOpen = () => {
  console.log("iopen");
};
const onCouponBtnClick = (data) => {
  if (data.id === couponsInfo.value.id) {
    couponsInfo.value = {};
  } else {
    couponsInfo.value = data;
  }
  showCoupon.value = false;
};
const getCouponList = async () => {
  const res = await couponList({
    pageNo: 1,
    pageSize: 100,
  });
  couponDataList.value = res.records || [];
};

// ---------------------------
const goDetail = () => {};

const goback = () => {
  back();
};

const currentPrice = ref(0)
const getRealPrice = async () => {
  const { total } = await getPrice({
    orderType: orderType.value,
    productId: productId.value,
    count: 1,
    couponsId: couponsInfo.value?.couponId || "",
  });
  currentPrice.value = total
  
};
watch(couponsInfo, getRealPrice);

const confirm = async () => {
  const params = {
    productId: productId.value,
    orderType: orderType.value,
    count: 1,
    couponsId: couponsInfo.value?.couponId || "", // 卡券信息
  };

  toast.loading("校验订单中...");
  try {
    await addOrder(params);
    toast.success("下单成功！");
    setTimeout(() => {
      back();
    }, 1600);
  } catch (err) {
    console.log("err-----", err);
  }
  console.log("query", params);
};
</script>

<style lang="less" scoped>
.orderDetail {
  .order-card {
    background: #f5f5f5;
    .order-header {
      padding: 8px;
    }

    .order-info {
      border-top: 1px dashed #eeeeee;
      padding: 16px;
      background: #fff;
      .label-value {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16px 0;
        &:not(:last-child) {
          border-bottom: 1px solid #eeeeee;
        }
        .value {
          color: #939393;
          font-size: 14px;
        }
      }
    }
  }

  .btns {
    width: 100vw;
    display: flex;
    align-items: center;
    justify-content: space-around;
    position: absolute;
    bottom: 8px;
  }

  .coupon-wrapper {
    height: 50vh;
    overflow: scroll;
    .coupon-list {
      padding-bottom: 8px;
      .item {
        position: relative;
        width: 343px;
        height: 94px;
        background: url("http://xishifile.oss-cn-hangzhou.aliyuncs.com/202307/25/1.png");
        background-size: 100% 100%;
        color: #fff;
        margin: 16px auto;
        display: flex;
        align-items: center;
        &:not(:last-child) {
          margin-bottom: 16px;
        }

        &.disabled {
          color: #999999;
          background: url("http://xishifile.oss-cn-hangzhou.aliyuncs.com/202307/25/2.png");
        }

        .price {
          font-size: 24px;
          width: 94px;
          height: 94px;
          flex-shrink: 0;
          text-align: center;
          line-height: 94px;
        }

        .order-info {
          width: 100%;
          height: 100%;
          padding: 0 16px;
          box-sizing: border-box;
          display: flex;
          flex-direction: column;
          justify-content: center;
          .title {
            white-space: pre-line; /*允许换行*/
            overflow: hidden;
            text-overflow: ellipsis; /*省略号*/
            display: -webkit-box;
            -webkit-box-orient: vertical; /*行向垂直排列*/
            -webkit-line-clamp: 2; /*限制2行*/
            font-size: 14px;
          }
          .time {
            font-size: 10px;
            color: #999999;
            margin-top: 8px;
          }
        }
        .coupon-btn {
          position: absolute;
          border: 1px solid #fff;
          right: 10px;
          display: inline-block;
          padding: 2px 8px;
          font-size: 12px;
          border-radius: 4px;
        }
      }
    }
  }
}
</style>
